// 权限校验
// 是否为首次获取登录用户
import router from "@/router";
import {useLoginUserStore} from "@/stores/user";
import {message} from "ant-design-vue";

let firstFetchLoginUser = true;
/**
 * 全局校验权限
 */
router.beforeEach(async(to,from,next)=>{
  const loginUserStore = useLoginUserStore()
  let loginUser = loginUserStore.loginUser
  // 确保页面刷新，首次加载时，能够等到后端返回信息后再进行校验
  if (firstFetchLoginUser) {
    await loginUserStore.fetchLoginUser()
    loginUser = loginUserStore.loginUser
    firstFetchLoginUser = false
  }
  const toUrl = to.fullPath
  if(toUrl.startsWith('/admin')){
    if(!loginUser || loginUser.userRole !== 'admin'){
      message.error('无权限访问')
      next(`/user/login?redirect=${to.fullPath}`) // 重定向到登录页，并携带当前访问路径作为跳转参数
      return
    }
  }
  next()
})
